package com.zusmart.core.proxy.support;

import com.zusmart.core.proxy.ProxyFactory;
import com.zusmart.core.proxy.ProxyHandler;
import com.zusmart.core.proxy.ProxyMethod;

public class ProxyChainForInstance extends AbstractProxyChain {

	private volatile int invokeIndex;

	public ProxyChainForInstance(Class<?> targetClass, Object targetInstance, Object[] targetArguments, ProxyMethod targetProxyMethod, ProxyHandler[] targetProxyHandlers) {
		super(targetClass, targetInstance, targetArguments, targetProxyMethod, targetProxyHandlers);
	}

	@Override
	protected Object doProxyChain(Object targetInstance, ProxyMethod proxyMethod) throws Throwable {
		Object result = null;
		if (this.invokeIndex < this.targetProxyHandlers.length) {
			ProxyHandler proxyHandler = this.targetProxyHandlers[this.invokeIndex++];
			if (null == proxyHandler) {
				throw new IllegalStateException("proxy handler is null");
			}
			ProxyFactory proxyFactory = proxyHandler.getFactory();
			if (null == proxyFactory) {
				throw new IllegalStateException("proxy factory is null");
			}
			result = proxyFactory.execute(this);
		} else {
			result = this.targetProxyMethod.invokeTargetMethod(this.targetInstance, this.targetArguments);
		}
		return result;
	}

}